package me.wangqu.weiyouqu.web.rest;

import com.codahale.metrics.annotation.Timed;
import me.wangqu.weiyouqu.domain.UserExtend;
import me.wangqu.weiyouqu.repository.UserExtendRepository;
import me.wangqu.weiyouqu.security.AuthoritiesConstants;
import me.wangqu.weiyouqu.security.SecurityUtils;
import me.wangqu.weiyouqu.web.rest.util.HeaderUtil;
import me.wangqu.weiyouqu.web.rest.util.PaginationUtil;
import me.wangqu.weiyouqu.web.rest.dto.UserExtendDTO;
import me.wangqu.weiyouqu.web.rest.mapper.UserExtendMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.annotation.Secured;
import org.springframework.web.bind.annotation.*;

import javax.inject.Inject;
import javax.validation.Valid;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.LinkedList;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;

/**
 * REST controller for managing UserExtend.
 */
@RestController
@RequestMapping("/api")
public class UserExtendResource {

    private final Logger log = LoggerFactory.getLogger(UserExtendResource.class);

    @Inject
    private UserExtendRepository userExtendRepository;

    @Inject
    private UserExtendMapper userExtendMapper;

    /**
     * 获取用户自己的资料
     *
     * @return
     */
    @RequestMapping(value = "/user-extends/self",
        method = RequestMethod.GET,
        produces = MediaType.APPLICATION_JSON_VALUE)
    @Timed
    public ResponseEntity<UserExtendDTO> getSelfUserExtend() {
        log.debug("REST request to get self UserExtend");
        return Optional.ofNullable(userExtendRepository.findOneByLogin(SecurityUtils.getCurrentUserLogin()))
            .map(result -> new ResponseEntity<>(
                userExtendMapper.userExtendToUserExtendDTO(result),
                HttpStatus.OK))
            .orElse(new ResponseEntity<>(
                new UserExtendDTO(),
                HttpStatus.OK));
    }

    /**
     * 更新用户自己资料
     *
     * @param userExtendDTO
     * @return
     * @throws URISyntaxException
     */
    @RequestMapping(value = "/user-extends/self",
        method = RequestMethod.POST,
        produces = MediaType.APPLICATION_JSON_VALUE)
    @Timed
    public ResponseEntity<UserExtendDTO> modifyUserExtend( @RequestBody UserExtendDTO userExtendDTO) throws URISyntaxException {
        log.debug("REST request to save UserExtend : {}", userExtendDTO);
        // 查询用户自身 userExtend
        String login = SecurityUtils.getCurrentUserLogin();
        userExtendDTO.setLogin(login);
        UserExtend result = userExtendRepository.findOneByLogin(login);
        if (result != null) {
            // userExtend 存在
            userExtendDTO.setId(result.getId()); // 设置ID 以便更新
            userExtendRepository.save(userExtendMapper.userExtendDTOToUserExtend(userExtendDTO));
        } else {
            // userExtend 不存在
            result = userExtendRepository.save(userExtendMapper.userExtendDTOToUserExtend(userExtendDTO));
        }
        return ResponseEntity.ok()
            .headers(HeaderUtil.createEntityUpdateAlert("userExtend", result.getId().toString()))
            .body(null);
    }

    /**
     * POST  /user-extends : Create a new userExtend.
     *
     * @param userExtendDTO the userExtendDTO to create
     * @return the ResponseEntity with status 201 (Created) and with body the new userExtendDTO, or with status 400 (Bad Request) if the userExtend has already an ID
     * @throws URISyntaxException if the Location URI syntax is incorrect
     */
    @RequestMapping(value = "/user-extends",
        method = RequestMethod.POST,
        produces = MediaType.APPLICATION_JSON_VALUE)
    @Timed
    @Secured(AuthoritiesConstants.ADMIN)
    public ResponseEntity<UserExtendDTO> createUserExtend(@Valid @RequestBody UserExtendDTO userExtendDTO) throws URISyntaxException {
        log.debug("REST request to save UserExtend : {}", userExtendDTO);
        if (userExtendDTO.getId() != null) {
            return ResponseEntity.badRequest().headers(HeaderUtil.createFailureAlert("userExtend", "idexists", "A new userExtend cannot already have an ID")).body(null);
        }
        UserExtend userExtend = userExtendMapper.userExtendDTOToUserExtend(userExtendDTO);
        userExtend = userExtendRepository.save(userExtend);
        UserExtendDTO result = userExtendMapper.userExtendToUserExtendDTO(userExtend);
        return ResponseEntity.created(new URI("/api/user-extends/" + result.getId()))
            .headers(HeaderUtil.createEntityCreationAlert("userExtend", result.getId().toString()))
            .body(result);
    }

    /**
     * PUT  /user-extends : Updates an existing userExtend.
     *
     * @param userExtendDTO the userExtendDTO to update
     * @return the ResponseEntity with status 200 (OK) and with body the updated userExtendDTO,
     * or with status 400 (Bad Request) if the userExtendDTO is not valid,
     * or with status 500 (Internal Server Error) if the userExtendDTO couldnt be updated
     * @throws URISyntaxException if the Location URI syntax is incorrect
     */
    @RequestMapping(value = "/user-extends",
        method = RequestMethod.PUT,
        produces = MediaType.APPLICATION_JSON_VALUE)
    @Timed
    @Secured(AuthoritiesConstants.ADMIN)
    public ResponseEntity<UserExtendDTO> updateUserExtend(@Valid @RequestBody UserExtendDTO userExtendDTO) throws URISyntaxException {
        log.debug("REST request to update UserExtend : {}", userExtendDTO);
        if (userExtendDTO.getId() == null) {
            return createUserExtend(userExtendDTO);
        }
        UserExtend userExtend = userExtendMapper.userExtendDTOToUserExtend(userExtendDTO);
        userExtend = userExtendRepository.save(userExtend);
        UserExtendDTO result = userExtendMapper.userExtendToUserExtendDTO(userExtend);
        return ResponseEntity.ok()
            .headers(HeaderUtil.createEntityUpdateAlert("userExtend", userExtendDTO.getId().toString()))
            .body(result);
    }

    /**
     * GET  /user-extends : get all the userExtends.
     *
     * @param pageable the pagination information
     * @return the ResponseEntity with status 200 (OK) and the list of userExtends in body
     * @throws URISyntaxException if there is an error to generate the pagination HTTP headers
     */
    @RequestMapping(value = "/user-extends",
        method = RequestMethod.GET,
        produces = MediaType.APPLICATION_JSON_VALUE)
    @Timed
    @Secured(AuthoritiesConstants.ADMIN)
    public ResponseEntity<List<UserExtendDTO>> getAllUserExtends(Pageable pageable)
        throws URISyntaxException {
        log.debug("REST request to get a page of UserExtends");
        Page<UserExtend> page = userExtendRepository.findAll(pageable);
        HttpHeaders headers = PaginationUtil.generatePaginationHttpHeaders(page, "/api/user-extends");
        return new ResponseEntity<>(userExtendMapper.userExtendsToUserExtendDTOs(page.getContent()), headers, HttpStatus.OK);
    }

    /**
     * GET  /user-extends/:id : get the "id" userExtend.
     *
     * @param id the id of the userExtendDTO to retrieve
     * @return the ResponseEntity with status 200 (OK) and with body the userExtendDTO, or with status 404 (Not Found)
     */
    @RequestMapping(value = "/user-extends/{id}",
        method = RequestMethod.GET,
        produces = MediaType.APPLICATION_JSON_VALUE)
    @Timed
    @Secured(AuthoritiesConstants.ADMIN)
    public ResponseEntity<UserExtendDTO> getUserExtend(@PathVariable Long id) {
        log.debug("REST request to get UserExtend : {}", id);
        UserExtend userExtend = userExtendRepository.findOne(id);
        UserExtendDTO userExtendDTO = userExtendMapper.userExtendToUserExtendDTO(userExtend);
        return Optional.ofNullable(userExtendDTO)
            .map(result -> new ResponseEntity<>(
                result,
                HttpStatus.OK))
            .orElse(new ResponseEntity<>(HttpStatus.NOT_FOUND));
    }

    /**
     * DELETE  /user-extends/:id : delete the "id" userExtend.
     *
     * @param id the id of the userExtendDTO to delete
     * @return the ResponseEntity with status 200 (OK)
     */
    @RequestMapping(value = "/user-extends/{id}",
        method = RequestMethod.DELETE,
        produces = MediaType.APPLICATION_JSON_VALUE)
    @Timed
    @Secured(AuthoritiesConstants.ADMIN)
    public ResponseEntity<Void> deleteUserExtend(@PathVariable Long id) {
        log.debug("REST request to delete UserExtend : {}", id);
        userExtendRepository.delete(id);
        return ResponseEntity.ok().headers(HeaderUtil.createEntityDeletionAlert("userExtend", id.toString())).build();
    }

}
